using System;
using System.IO;
using System.Web;
using log4net;

namespace Sherwood.Content.UpdateServices.Attachments
{
    public class QueuedAttachmentPersister : IAttachmentPersister
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(QueuedAttachmentPersister));

        public void AddAttachment(IAttachmentMeta meta, string referenceId, string url, string fileExtension)
        {
            var attachment = meta.GetOrCreateAttachment(referenceId) as IDownloadableAttachment;
            if(attachment == null)
                throw new InvalidOperationException("Cannot use QueuedAttachmentPersister on attachments not implementing IDownloadableAttachment");

            var fileName = Path.GetFileNameWithoutExtension(url);
            var extension = (string.IsNullOrEmpty(fileExtension) ? Path.GetExtension(url) : "." + fileExtension);
            attachment.BeginDownload(url, HttpUtility.HtmlDecode(fileName) + extension);
        }

        public void UpdateAttachment(IAttachmentMeta meta, IAttachment attachment, string url, string fileExtension)
        {
            AddAttachment(meta, attachment.ReferenceId, url, fileExtension);
        }

        public void DeleteAttachment(IAttachmentMeta meta, IAttachment value)
        {
            meta.DeleteAttachment(value.ReferenceId);
        }
    }
}